#!/usr/bin/env node

import fs from "fs";
import rimraf from "rimraf";
import colors from "colors";
import { promisify } from "util";
import path, { basename } from "path";
// import mkdirp from "mkdirp";
// import glob from "glob";
// import colors from "colors";
import { toJSON } from "cssjson";
import { template } from "lodash";
import { extend } from "umi-request";
import { getConfig } from "../libs/getConfig";
import { getTemplate } from "../libs/getTemplate";
import { downloadFileAsync } from "../libs/downloadFileAsync";

const config = getConfig();
const request = extend({});

const render = template(getTemplate("icon.hml"));
const renderCSS = template(getTemplate("icon.css"));
const renderJs = template(getTemplate("icon.js"));
const renderVanCSS = template(getTemplate("van-icon.less"));
const renderVanTs = template(getTemplate("van-icon.ts"));

async function createOpenharmonyIcon() {
  console.log(colors.yellow(`🔨  Building fresh icons...`));

  const {
    symbol_url,
    save_dir,
    icon_prefix,
    trim_icon_prefix,
    default_icon_size,
    prefix_cls,
    use_vant,
  } = config;
  const symbolCode = symbol_url
    .match(/font_(.+?).css/)?.[0]
    ?.replace(".css", "");
  const saveDir = path.resolve(save_dir);
  const fileName = basename(save_dir) || "iconfont";
  const saveFont = path.join(saveDir, `${symbolCode}.ttf`);

  await promisify(rimraf)(saveDir);
  try {
    await promisify(fs.access)(saveDir);
  } catch (err) {
    await promisify(fs.mkdir)(saveDir);
  }

  await downloadFileAsync(`http://at.alicdn.com/t/${symbolCode}.ttf`, saveFont);
  const data: string = await request.get(symbol_url);
  const map: Record<string, any> = toJSON(data).children;
  const newMap: Record<string, any> = {};
  Object.keys(map)
    .filter((v) => v.search(icon_prefix) === 1)
    .forEach((k) => {
      let key = k.substr(1).replace(":before", "");
      if (trim_icon_prefix) key = key.replace(icon_prefix, "");
      const content = map[k]?.attributes?.content
        ?.replace('"\\e', "\\ue")
        ?.replace('"', "");
      newMap[key] = content;
    });
  const mapJson = JSON.stringify(newMap, null, 2).replace(/"\\/g, '"');

  if (use_vant) {
    fs.writeFileSync(
      path.join(saveDir, fileName + ".hml"),
      getTemplate("van-icon.hml")
    );
    fs.writeFileSync(
      path.join(saveDir, fileName + ".less"),
      renderVanCSS({
        prefix_cls,
        symbolCode,
        save_dir: "/node_modules/oh-vant/lib/" + save_dir.split('/')[2],
      })
    );

    fs.writeFileSync(
      path.join(saveDir, fileName + ".ts"),
      renderVanTs({ prefix_cls, default_icon_size, map: mapJson })
    );
  } else {
    fs.writeFileSync(
      path.join(saveDir, fileName + ".hml"),
      render({ prefix_cls })
    );
    fs.writeFileSync(
      path.join(saveDir, fileName + ".css"),
      renderCSS({ prefix_cls, symbolCode, save_dir: save_dir.substr(1) })
    );

    fs.writeFileSync(
      path.join(saveDir, fileName + ".js"),
      renderJs({ prefix_cls, default_icon_size, map: mapJson })
    );
  }

  console.log(
    `\n${colors.green("√")} All icons have been putted into dir: ${colors.green(
      config.save_dir
    )}\n`
  );
}

createOpenharmonyIcon();
